package com.gexin.app.service.impl;

import com.gexin.app.entity.Category;
import com.gexin.app.mapper.CategoryMapper;
import com.gexin.app.mapper.QuestionMapper;
import com.gexin.app.request.category.CategoryDto;
import com.gexin.app.service.QuestionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class QuestionServiceImpl implements QuestionService {


    @Resource
    private CategoryMapper categoryMapper;


    @Override
    public Boolean addCategory(String name, Long parentId) {

        // 最顶级分类的parentId值为-1
        if (parentId != -1) {
            Category ca = categoryMapper.selectCategoryById(parentId);
            if (ca == null) {
                log.error("fail to found the category, id = {}", parentId);
                return false;
            }
        }

        List<Category> categories = categoryMapper.selectSubCategoriesById(parentId);
        if (categories != null) {
            boolean hasCategory = false;
            for (Category category : categories) {
                if (category.getName().equals(name)) {
                    hasCategory = true;
                    break;
                }
            }
            if (hasCategory) {
                log.error("repeated name: {}", name);
                return false;
            }
        }
        int effected = categoryMapper.insert(new Category(name, parentId));
        if (effected != 1) {
            log.error("insert err, name: {} ,parentId: {}", name, parentId);
            return false;
        }
        return true;

    }

    @Override
    public List<CategoryDto> getSubCateByParentId(Long id) {
        List<Category> categories = categoryMapper.selectSubCategoriesById(id);
        return categories.stream().map(category -> new CategoryDto(category.getId(), category.getName(), category.getParentId())).collect(Collectors.toList());

    }
}
